package cn.simon.free.redis.redisson.lock;

import cn.simon.free.redis.redisson.common.RedissonCommon;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redisson分布式锁实现
 *
 * @author simon
 * @date 2020/11/18 13:38
 * @copyright:
 * @modifier
 * @motto a no talent, people who have to study hard
 */
@Slf4j
@Component
public class RedissonLockSupport extends RedissonCommon implements RedissonLock {

    @Override
    public void lock(String lockKey) {
        redissonClient.getLock(lockKey).lock();
    }

    @Override
    public void unlock(String lockKey) {
        redissonClient.getLock(lockKey).unlock();
    }

    @Override
    public void lock(String lockKey, int timeout) {
        redissonClient.getLock(lockKey).lock(timeout, TimeUnit.SECONDS);
    }

    @Override
    public void lock(String lockKey, TimeUnit unit, int timeout) {
        redissonClient.getLock(lockKey).lock(timeout, unit);
    }

    @Override
    public boolean tryLock(String lockKey) {
        return redissonClient.getLock(lockKey).tryLock();
    }

    @Override
    public boolean tryLock(String lockKey, long waitTime, long leaseTime, TimeUnit unit) {
        try {
            return redissonClient.getLock(lockKey).tryLock(waitTime, leaseTime, unit);
        } catch (InterruptedException e) {
            log.error("redis tryLock exception:{}", lockKey, e);
            return false;
        }
    }

    @Override
    public boolean isLocked(String lockKey) {
        return redissonClient.getLock(lockKey).isLocked();
    }
}
